package com.crl.ui.bitmaps
{
	
	import flash.display.BitmapData;
	import flash.display.FrameLabel;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.geom.Matrix;
	import flash.geom.Rectangle;
	import flash.utils.Dictionary;
	
	public class Conversor
	{
		
		static private var cache:Dictionary=new Dictionary(true);
		
		public function Conversor()
		{
			throw new Error("不能创建实例");
		}
		
		
		static public function convertir(movieClip:MovieClip):Array
		{
			if (cache[movieClip] != null){
				return cache[movieClip];
			}
			
			var oldBitmapData:BitmapData;
			var frames:Array = [];
			for (var frame:uint = 1; frame <= movieClip.totalFrames; frame++)
			{
				movieClip.gotoAndStop(frame);
				
				var rectangle:Rectangle = movieClip.getBounds(movieClip);
				var bitmapData:BitmapData = new BitmapData(
					Math.max(1, rectangle.width),
					Math.max(1, rectangle.height),
					true,
					0x00000000
				);
				var mat:Matrix = new Matrix();
				mat.translate(-rectangle.x, -rectangle.y);
				bitmapData.draw(movieClip, mat);
				
				if (oldBitmapData != null && bitmapData.compare(oldBitmapData) == 0)
				{
					bitmapData.dispose();
					bitmapData = oldBitmapData;
				}
				
				var frameLabel:FrameLabel;
				for each (var frameLabelMovieClip:FrameLabel in movieClip.currentLabels){
					if (frameLabelMovieClip.frame == frame){
						frameLabel = frameLabelMovieClip;
					}
				}
				
				frames[frames.length] = new BitmapFrame(
					bitmapData,
					rectangle,
					frameLabel
				);
				oldBitmapData = bitmapData;
			}
			
			cache[movieClip] = frames;
			return frames;
		}
		
		
		static public function convertirSprite(sprite:Sprite):BitmapData
		{
			if (cache[sprite] != null){
				return cache[sprite];
			}
			
			var rectangulo:Rectangle = sprite.getBounds(sprite);
			var bitmapData:BitmapData = new BitmapData(
				Math.max(1, rectangulo.width),
				Math.max(1, rectangulo.height),
				true, 0x00000000
			);
			var matriz:Matrix = new Matrix();
			matriz.translate(-rectangulo.x, -rectangulo.y);
			bitmapData.draw(sprite, matriz);
			
			cache[sprite] = bitmapData;
			
			return bitmapData;
		}
	}
}